const app = getApp()
const util = require('../../utils/util.js')

Page({
  data: {
    title: '',
    imagePath: "",
    isCanvasOk: false,
    inputList: [],
    extraInputMsg:[], // inputList中skip的信息，用于页面展示信息以外的信息(如，时间等自动生成的信息)
    image_w: '',
    image_h: '',
    flags: {},
    erweima: {},

    id: 0,
    title:'',
    selectArr:null,
    selectTitle:'',
    selectQrcodeArr:null,  // select选项对应id
    isHandWrite:0, // 是否需要手写体
  },

  onLoad: function(options) {
    this.getConfig()
    this.getItemById(options.id)

    this.setData({
      id: options.id,
      title: options.title
    })
  },

  onShareAppMessage: function() {
    return {
      title: '快来恶搞你的' + this.data.title + '吧!',
      path: "/pages/index/index",
    }
  },

  getConfig: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'config?version=' + app.globalData.version,
      success: function(res) {
        if (res.data.data) {
          that.setData({
            flags: res.data.data
          })
        }
      }
    })
  },

  // 通过id获取item的参数----imagePath: res.data.data.image,
  getItemById: function(id) {
    var that = this
    wx.request({
      url: app.globalData.url + 'get/id/' + id,
      success: function(res) {
        var inputDate = res.data.data.config
        that.setData({
          inputList: inputDate,
          title: res.data.data.title,
          imagePath: res.data.data.image,
          erweima: res.data.data.qrcode_config[0],
          isHandWrite:res.data.data.need_font
        })
        // console.log(res.data.data);
        
        for(let i = 0 ; i < inputDate.length ; i ++){
          if( inputDate[i].isSkip ){
            var temp = that.data.extraInputMsg
            temp.push(inputDate[i])
            
            that.setData({
              extraInputMsg: temp,
            })           
          }
        }

        // select下拉选择
        if(inputDate[0].type == 'select'){
          // data[0] 记录select值，转数组
          var arr = [];
          var arrId = [];
          var obj = inputDate[0];
          var objId = inputDate[1];
          for(let i in obj){
            arr.push(obj[i]);
          }
          for(let j in objId){
            arrId.push(objId[j]);
          }
          //
          that.setData({
            selectTitle: arr[1],
            selectArr: arr.slice(2 , arr.length),
            selectQrcodeArr: arrId,
            inputList: inputDate.slice(2 , inputDate.length)
          })
          // 图片转临时路径
          wx.downloadFile({
            url: that.data.imagePath,
            success: (res)=>{
              that.setData({
                imagePath : res.tempFilePath
              })
            },
          });
        }
        // 无需填写信息，直接保存
        if(inputDate[0].type == 'skip'){
          wx.downloadFile({
            url: that.data.imagePath,
            success: (res)=>{
              that.setData({
                imagePath : res.tempFilePath,
                isCanvasOk: true
              })
            },
          });
        }
      }
    })
  },

  //将姓名绘制到canvas的固定
  setName: function(ctx, name, x, y, fontSize, fontColor, rotate) {
    var that = this
    ctx.setFontSize(fontSize)
    ctx.setFillStyle(fontColor)
    ctx.save()
    ctx.translate(x, y)
    ctx.rotate(rotate * Math.PI / 180)
    ctx.fillText(name, 0, 0)
    ctx.restore()
    ctx.stroke()
  },

  //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg: function(names) {
    var that = this
    var shareflag = this.data.flags.shareflag
    // 获取canvas实例
    var canvas = wx.createCanvasContext('mycanvas')
    var path = this.data.imagePath
    
    var inputList = that.data.inputList
    
    wx.getImageInfo({
      src: path,
      success: function(res) {
        that.setData({
          image_w: res.width,
          image_h: res.height,
        })
        canvas.drawImage(res.path, 0, 0, res.width, res.height)
        
        // inputList中skip数据处理
        var extraDate = that.data.extraInputMsg;
        var namesToArr = Object.keys(names);
        for(let i = 0 ; i < extraDate.length ; ++i){
          if(extraDate[i].dateFormat != 'null'){
            // 生成指定格式的时间
            names["name"+ (namesToArr.length + i)] = util.getCustomTime(extraDate[i].dateFormat);
          }else if(extraDate[i].randomNumberLength != 'null'){
            // 生成随机数字
            names["name"+ (namesToArr.length + i)] = util.randomNumber(extraDate[i].randomNumberLength);
          }
        }

        if(that.data.title == "拆迁记录"){
          names['name2'] = that.fmoney( parseInt(names['name2']) )
          names['name4'] = names['name1'] + '您的尾号7141的账号于' + util.YMDHMS(new Date()) + '他行转入金额RMB' + that.fmoney( parseInt(names['name2']) ) + '，当前余额为' + that.fmoney(parseInt(names['name2'])+302) + ' 【' +  names['name3'] + '】'
          var duanxin = {
            fontColor:"#111111",
            fontSize:"24",
            maxlength:"2",
            rotate:"0",
            x:"50",
            y:"254"
          }
          inputList.pop();
          inputList.pop();
          inputList.pop();
          inputList.push(duanxin);
          names['name1'] = names['name4']
          delete names.name2
          delete names.name3
          delete names.name4
          // 拆分-重构
          var chr = names['name1'].split("");
          var temp = "";
          var row = [];
          for (var a = 0; a < chr.length; a++) {
            if (canvas.measureText(temp).width < 160) {} 
            else {
                row.push(temp);
                temp = "";
            }
            temp += chr[a];
          }
          row.push(temp);
          names['name1'] = row[0]
          var duanxin2 = {
            fontColor:"#111111",
            fontSize:"24",
            maxlength:"2",
            rotate:"0",
            x:"50",
            y:"285"
          }
          inputList.push(duanxin2);
          names['name2'] = row[1]
          var duanxin3 = {
            fontColor:"#111111",
            fontSize:"24",
            maxlength:"2",
            rotate:"0",
            x:"50",
            y:"315"
          }
          inputList.push(duanxin3);
          names['name3'] = row[2]
          var duanxin4 = {
            fontColor:"#111111",
            fontSize:"24",
            maxlength:"2",
            rotate:"0",
            x:"50",
            y:"345"
          }
          inputList.push(duanxin4);
          names['name4'] = row[3]
        }

        // 循环画input值
        for (var i = 0; i < inputList.length; i++) {
          var itemLists = inputList[i]
          that.setName(canvas, names["name" + i + ""], itemLists.x, itemLists.y, itemLists.fontSize, itemLists.fontColor, itemLists.rotate)
        }

        // 画二维码
        if (shareflag) {
          var ewm;
          if (that.data.erweima.type == '0') {
            // 小程序码
            ewm = '/images/ewm_r.png'
            canvas.drawImage(ewm, res.width - 156, res.height - 156, 150, 150)
          } else if (that.data.erweima.type == 1) {
            // 方形二维码
            ewm = '/images/ewm_f.png'
            var size = parseInt(that.data.erweima.size)
            canvas.drawImage(ewm, that.data.erweima.x, that.data.erweima.y, size, size)
          }
        }

        //绘制图片
        canvas.draw()
        // 将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
        setTimeout(function() {
          wx.canvasToTempFilePath({
            canvasId: 'mycanvas',
            success: function(res) {
              that.setData({
                imagePath: res.tempFilePath,
                isCanvasOk: true
              })
            },
            fail: function(res) {
              console.log(res)
            }
          })
          wx.hideLoading()
        }, 200)
      }
    })
  },

  //点击图片进行预览
  previewImg: function(e) {
    if (e.currentTarget.dataset.key) {
      var img = this.data.imagePath
      wx.previewImage({
        current: img,
        urls: [img]
      })
    }
  },

  // 提交表单
  formSubmit: function(e) {
    var that = this;
    wx.showLoading({
      title: '图片生成中...',
      icon: 'loading',
    })
    var reg = /^\d+(\.\d+)?$/;
    var value = e.detail.value;

    if(!that.data.isHandWrite){
      // 不需要手写字体
      if(that.data.title == '支付宝年度账单'){
        // 年账单
        if( reg.test(value.name0) ){
          value.name0 = that.fmoney( value.name0 , 2);
          value.name1 = ( parseInt(value.name1) + Math.random() + '').slice(0,5) + '%';
        }
      }
      if(that.data.title == '压力山大'){
        var inputList = that.data.inputList
        // 根据不同性别加载不同图片
        var sex = that.data.selectQrcodeArr[that.data.index];
        if(sex == 'male'){
          value.name1 = value.name1 + "  " + value.name2 + '岁';
          inputList.pop();
        }else if(sex == "female"){
          // 刷新图片
          that.setData({
            imagePath:'https://xcx-1256535092.cos.ap-shanghai.myqcloud.com/suinigao/item/pressure/pressure_female.jpg',
          })
          value.name1 = value.name1 + "  " + value.name2 + '岁';
          inputList[0].x = 580;
          inputList[0].y = 240;
          inputList[1].x = 425;
          inputList[1].y = 275;
          inputList.pop();
        }else{}
        // delete names.name2;
      }

      this.createNewImg(value)
    }else{
      // 需要手写字体，直接发送服务器，直接获取图片
      if(that.data.title == '购车合同'){
        if(!that.data.selectQrcodeArr[that.data.index]){
          wx.showToast({
            title: '请选择购买车辆',
            icon: 'none',
            duration: 1500,
            mask: false,
          });
          return;
        }
        wx.request({
          url: app.globalData.url + 'buycar',
          data: {
            type: that.data.selectQrcodeArr[that.data.index],
            name: value.name0,
            version: app.globalData.version
          },
          method: 'POST',
          success: (res)=>{
            that.setData({
              imagePath: res.data.data,
              isCanvasOk: true
            })
            wx.hideLoading()
          },
        });
      }

    }
  },

  // 保存图片
  toSave: function() {
    var that = this;
    var shareflag = this.data.flags.shareflag
    wx.showLoading({
      mask: true,
      title: "保存中"
    })
    that.saveImageToPhotosAlbum(that.data.imagePath)
    
  },

  // 保持图片到本地相册
  saveImageToPhotosAlbum: function(imagePath){
    var that = this;
    // console.log(imagePath);
    if( imagePath.indexOf("tmp" == -1) ){
      wx.downloadFile({
        url: imagePath,
        success: (res)=>{
          that.setData({
            imagePath : res.tempFilePath
          })
        },
      });
    }
    
    wx.saveImageToPhotosAlbum({
      filePath: imagePath,
      success: (res) => {
        wx.hideLoading()
        wx.showModal({
          title: "保存成功",
          content: that.data.flags.hua,
          showCancel: false
        })
      },
      fail: function(error) {
        wx.hideLoading();
        console.log(error);
        wx.getSetting({
          success(settingdata) {
            console.log(settingdata)
            if (settingdata.authSetting['scope.writePhotosAlbum']) {
              console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
            } else {
              console.log('获取权限失败，给出不给权限就无法正常使用的提示')
            }
          }
        })
      }
    })
  },

  bindPickerChange: function(e){
    this.setData({
      index: e.detail.value
    })
  },

  fmoney: function(s, n) { 
    n = n > 0 && n <= 20 ? n : 2; 
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; 
    var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1]; 
    var t = ""; 
    for (let i = 0; i < l.length; i++) { 
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : ""); 
    } 
    return t.split("").reverse().join("") + "." + r; 
  },
  
})